import {mapGetters} from "vuex";
import UvUpload from '@/components/school/uv-upload';
import * as TaskInfoApi from '@/api/school/taskInfo.js';
import * as GroupInfoApi from '@/api/school/groupinfo.js';
import {AgreementEnum,} from '@/utils/dict.js';

import diyJson from '@/config/diy.js';
import {createGroup} from "../../../../api/school/groupinfo";

export const mixins =
    {
      computed: mapGetters(['schoolId', 'userInfo']),
      components: {
        UvUpload,
      },
      data() {
        return {

          datetimePicker: {
            value: '',
            minDate: Number(new Date().setMinutes(new Date().getMinutes() + 30)),
            maxDate: Number(new Date().setHours(new Date().getMinutes() + 72)),
          },
          rules: {
            'activityName': {
              type: 'string',
              required: true,
              message: '拼团名称',
              trigger: ['blur', 'change']
            }, 'activityRule': {
              type: 'string',
              required: true,
              message: '请填写活动规则说明',
              trigger: ['blur', 'change']
            },
            // 'endTime': {
            //   type: 'string',
            //   required: true,
            //   message: '请输入活动结束时间',
            //   trigger: ['blur', 'change']
            // }, 'identityType': {
            //   type: 'string',
            //   required: true,
            //   message: '请选发布身份',
            //   trigger: ['blur', 'change']
            // }, 'deliveryTimeStart': {
            //   type: 'number',
            //   required: true,
            //   message: '',
            //   trigger: ['blur', 'change']
            // }
            // , 'deliveryTimeEnd': {
            //   type: 'number',
            //   required: true,
            //   message: '选择配送结束时间',
            //   trigger: ['blur', 'change']
            // },

            'actionAddress': {
              type: 'string',
              required: true,
              message: '请选择任务地址',
              trigger: ['blur', 'change']
            },
          },

          btnDisabled: false,

          themConfig: diyJson.commonStyle,

          pageBody: {
            scrollTop: 0,
          },

          statusNavProperties: { // 筛选条件
            title: "订单池",
            setStyle: {
              bgColor: "white",
              enableBack: true,
              titleColor: "rgba(100, 101, 102)",
              titleStyle: {}
            }
          },

          isReadAggreement: [],

          photos: [],

          form: {
            "activityName": "",
            "actionAddress": "",
            "activityRule": "",
            "allowGroupProcessingTakeOrder": false,
            "endTime": "",
            "groupSuccessAutoTake": true,
            "finishAutoGroup": true,
            "remark":"",
            "schoolId": "",
            "identityType":2,
            "goodsInfos": [
              // {
              //   "goodsId": "101242368874774529",
              //   "skuId": "7812910212",
              // 折扣模式：1=折扣；2=现金优惠
              //   "discountMode": 1,
              //   "discountValue": 6,
              //   "errandChargeAmount": 0,
              //   "minNumber": 2,
              //   "maxNumber": 2
              // }
            ],
            "deliveryTimeStart": "",
            "deliveryTimeEnd": ""
          },
          selectTaskObj:null,
          selectTaskIndex: null,
          selectSku:null,
          selectSkuRadioModel:null,
          // 1=目的地，2=始发地
          useAddressType: 2,
          useAddress: [],
          useAddressData: [],
          taskInfos: []
        };
      },

      onLoad: function (options) {

        let p = options.params;
        if (p) {
          let params = JSON.parse(p);
          console.log("params", params)
          this.statusNavProperties.title = params.titleName;
          this.form.taskId = params.taskId;
        }
      },

      onShow() {
        this.getTaskInfos({schoolId:this.schoolId});
        this.form.schoolId=this.schoolId;
      },
      mounted() {

      },

      methods: {

        getTaskInfos(params) {
          TaskInfoApi.getTaskInfos(params).then(res => {
            this.taskInfos = res.data
          })
        },

        selectTask(item,index){
            this.form.goodsInfos=[
              {
                  "goodsId": item.id,
                  "skuId": "",
                  // 折扣模式：1=折扣；2=现金优惠
                  "discountMode": 1,
                  "discountValue": 10,
                  "errandChargeAmount": 0,
                  "minNumber": 3,
                  "maxNumber": 3
              }
            ]
          this.selectTaskIndex = index;
          this.selectTaskObj = item;

          // 至空 重新选择
          this.selectSku = null;
          this.selectSkuRadioModel = null;
          this.form.goodsInfos[0]['skuId']= '';
        },

        skuSelect(e,item){
          this.selectSku = item;
          this.form.goodsInfos[0]['skuId']=item.skuId;
        },

        // 打开时间选择框
        openDatePick(field) {
          if (field==='endTime'){
            this.$refs.datetimePicker.open();
          }else if (field==='deliveryTimeStart'){
            this.$refs.deliveryTimeStart.open();
          }else {
            this.$refs.deliveryTimeEnd.open();
          }
        },

        // 选择时间回调
        checkExpireDate(e,field) {
          // console.log("时间",new Date(e.value));

          var date = new Date(e.value); // 转换为Date对象

          // 获取年月日时分秒
          var year = date.getFullYear();
          var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
          var day = ('0' + date.getDate()).slice(-2);
          var hours = ('0' + date.getHours()).slice(-2);
          var minutes = ('0' + date.getMinutes()).slice(-2);
          // var seconds = ('0' + date.getSeconds()).slice(-2);

          // 组合成 yyyy-mm-dd HH:mm:ss 格式
          let dateStr = `${year}-${month}-${day} ${hours}:${minutes}:00`;
          if (field==='endTime'){
            // this.form.endTime = dateStr;
            this.form = {
              ...this.form,
              endTime:dateStr
            }
          }else if (field==='deliveryTimeStart'){
            // this.form.deliveryTimeStart = dateStr;
            this.form = {
              ...this.form,
              deliveryTimeStart:dateStr
            }
          }else {
            // this.form.deliveryTimeEnd = dateStr;
            this.form = {
              ...this.form,
              deliveryTimeEnd:dateStr
            }
          }

        },

        datePickerformatter(type, value) {
          if (type === 'year') {
            return `${value}年`
          }
          if (type === 'month') {
            return `${value}月`
          }
          if (type === 'day') {
            return `${value}日`
          }

          if (type === 'hour') {
            return `${value}时`
          }

          if (type === 'minute') {
            return `${value}分`
          }
          return value
        },

        // 快捷选择时间
        setExpireTime(v) {
          let d = new Date();
          if (v < 1) {
            d.setMinutes(d.getMinutes() + (v * 60));
          } else {
            d.setHours(d.getHours() + v);
          }
          this.checkExpireDate({value: Number(d)},'endTime')
        },


        // 输入金额变化
        amountInputChange(e) {
          this.$nextTick(() => {
            this.form.amount = parseFloat(e).toFixed(2);
          });
          console.log("amount", this.form.amount)
        },

        // 选择常用金额
        useAmount(e) {
          this.form.amount = e;
        },

        agreementReadClick(e) {
          this.form.isRead = e;
        },

        /**
         * 上传结果
         * @param array [
         *   {
         *     images:[{'url':''}],
         *     params:'',
         *   }
         * ]
         */
        uploadSuccess(array) {
          console.log("array", array)
          let photos = [];
          for (let i = 0; i < array.images.length; i++) {
            photos.push(array.images[i].url);
          }
          this.form.photos = photos;
          console.log("form", this.form)
        },

        // 提交表单
        submit() {
          if (!this.form.isRead) {
            this.$refs.notify.show({
              message: '请阅读协议声明',
              type: 'warning',
              duration: 1000,
              safeAreaInsetTop: true
            });
            return;
          }
          console.log("form", this.form);

          if (this.form.goodsInfos==null||this.form.goodsInfos.length<=0){
            uni.showToast({
              title: '请选择拼团任务',
              icon: 'none',
              duration: 2000
            });
            return;
          }

          if (this.form.goodsInfos==null||this.form.goodsInfos.length<=0){
            uni.showToast({
              title: '请选择拼团任务',
              icon: 'none',
              duration: 2000
            });
            return;
          }

          if (!this.form.goodsInfos[0]['skuId']){
            uni.showToast({
              title: '请选择任务规格',
              icon: 'none',
              duration: 2000
            });
            return;
          }

          // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
          this.$refs.form.validate().then(res => {

            GroupInfoApi.createGroup(this.form).then(res=>{
              uni.showToast({
                title: '创建成功',
                icon: 'none',
                duration: 2000
              });
              setTimeout(()=>{
                uni.navigateBack();
              },1000)
            });

          }).catch(errors => {
            console.log("eee", errors)
          })
        },

        readAgreement() {
          uni.navigateTo({
            url: `/pages/users/privacy/index?params=${encodeURIComponent(
                JSON.stringify(AgreementEnum.pushTask))}`
          })
        },

        getApp() {
          return app;
        },
      },
      onReachBottom() {

      }
    }
